//
//  DBManager.m
//  PostMessa
//
//  Created by never down on 15-5-12.
//  Copyright (c) 2015年 ygy_ios. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "DBManager.h"


@class User,Store,Product,Statistic,Order;
static DBManager *shareDBManager = nil;

@implementation DBManager
BOOL initContents = YES;
@synthesize databasePath = _databasePath;

//static 静态
+(DBManager *) shareDBManagerInstance{
    //支持多线程
    @synchronized(self){
        if (shareDBManager == nil) {
            shareDBManager = [[DBManager alloc] init];
        }
    }
    return shareDBManager;
}

-(id)initWithDbPath:(NSString *)DBPath{
    self = [super init];
    if (self != nil) {
        if (DBPath) {
            _databasePath = [[NSString alloc]initWithString:DBPath];
        }
    }
    return self;
}



#pragma mark - core data stack
/** 获取Documents路径 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                   inDomains:NSUserDomainMask] lastObject];
}

-(NSManagedObjectContext *)manageObjectContext{
    if(_managedObjectContext != nil){
        return _managedObjectContext;
    }
    //produce a new managedObjectContext  by    _persistentStoreCoordinator
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [NSManagedObjectContext new];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    
//    if(_managedObjectContext == nil){
//        return nil;
//    }
//    id hasInit = [[NSUserDefaults standardUserDefaults] objectForKey:@"initFinished"];
//    if (!hasInit || ([hasInit isKindOfClass:[NSNumber class]] && ![(NSNumber *)hasInit boolValue])) {
//        [self initDBContents:_managedObjectContext];
//        [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"initFinished"];
//    }
    
    return _managedObjectContext;
}

-(NSManagedObjectModel *)managedObjectModel{
    if(_managedObjectModel != nil){
        return _managedObjectModel;
    }
    //数据模型路径
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:DB_MODELNAME ofType:@"momd"];
    if (modelPath) {
        //
        _managedObjectModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL URLWithString: modelPath]];
    }
    return _managedObjectModel;
}


-(NSPersistentStoreCoordinator *)persistentStoreCoordinator{
    if(_persistentStoreCoordinator != nil){
        return _persistentStoreCoordinator;
    }
    NSError *error = nil;
    NSURL *storeUrl = nil;
    //得到数据库的路径
        //在本地文件系统中产生持久化文件
        //storeUrl = [NSURL fileURLWithPath:_databasePath];
    storeUrl = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:DB_NAME];
    
    
    
    //通过“数据模型路径”对象 来产生 新的objectModel对象
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:[self managedObjectModel]];
    
    if(_persistentStoreCoordinator == nil){
        return nil;
    }
    
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                                   configuration:nil
                                                   URL:storeUrl
                                                   options:nil
                                                   error:&error ]) {
        NSLog(@"Unresolved error %@,%@",error,[error userInfo]);
        //请问这里是干什么用的？！！
        abort();
        
    }
    
    return _persistentStoreCoordinator;
}


//从数据源到持久层数据库的转换函数
-(BOOL)initDBContents:(NSManagedObjectContext *)context{
    if(!self->initContents){
        return NO;
    }
    NSEntityDescription *userEn = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    
    
    User *aUser = [NSEntityDescription insertNewObjectForEntityForName:[userEn name] inManagedObjectContext:context];
    aUser.uid = [[NSNumber alloc]initWithInteger:1];
    aUser.name = @"zhang";
    aUser.age = [[NSNumber alloc]initWithInteger:10];
    aUser.rank = [[NSNumber alloc]initWithInteger:10];
    aUser.role = [[NSNumber alloc]initWithInteger:10];
    aUser.sex = [[NSDecimalNumber alloc]initWithInt:1];
    aUser.tel = nil;
    aUser.image = nil;
    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Unresolved error %@, %@",error,[error userInfo]);
        abort();
    }else{
        return YES;
    }

}

-(void)createItemDB{
    NSArray * documentsPaths;
    NSString * docDir;
    
    documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docDir = [documentsPaths objectAtIndex:0];
    _databasePath = [[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:@"postMessa.db"]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:_databasePath]) {
        const char * dbPath = [_databasePath UTF8String];
        if(sqlite3_open(dbPath, &itemsDB) == SQLITE_OK){
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS USER(UID INTEGER PRIMARY KEY AUTOINCREMENT, sex TEXT, age TEXT, name TEXT, role TEXT, tel TEXT, rank TEXT, image TEXT)";
            
            if(sqlite3_exec(itemsDB, sql_stmt, NULL, NULL, &errMsg) == SQLITE_OK){
                NSLog(@"create table user successs!");
            }else{
                NSLog(@"create table user failed!");
            }
        }else{
            NSLog(@"connect or create database failed!");
        }
//        _managedObjectContext = [self manageObjectContext];
//        [self initDBContents:_managedObjectContext];
//        User *u = [self fetchUser];
//        NSLog(@"%@",u.name);
    }else{
        NSLog(@"sqlite dadabase is existed.");
        [self getAllUserList];
    }
    
//    if (sqlite3_open([_databasePath UTF8String], &database)==SQLITE_OK) {
//        NSLog(@"sqlite dadabase is opened."); }
//    else{
//        NSLog(@"sqlite dadabase is not existed.");
//    }
}

-(NSArray *)fetchUser{
    NSManagedObjectContext * context = nil;
    NSEntityDescription * userEntity = nil;
    
    //查询请求对象
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    //sortDescriptor
    NSSortDescriptor *sortDescriptor = nil;
    NSArray *arrList = nil;
    NSError *error = nil;
    
    context = [self manageObjectContext];
    if (context == nil) {
        return nil;
    }
    //获取表对象
    userEntity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:context];
    [request setEntity:userEntity];
    //
//    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"uid" ascending:YES];
    
    //
//    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    //
    arrList = [context executeFetchRequest:request error:&error];
    
    if (arrList && arrList.count > 0) {
        NSLog(@"%@",(User *)[arrList objectAtIndex:0]);
//        return  (User *)[arrList objectAtIndex:0];
        return arrList;
    }
    return nil;
}

#pragma mark - sql

-(void)insertUser{
    NSEntityDescription *userEn = [NSEntityDescription entityForName:@"User" inManagedObjectContext:[self manageObjectContext]];
    
    User *aUser = [NSEntityDescription insertNewObjectForEntityForName:[userEn name] inManagedObjectContext:[self manageObjectContext]];
    aUser.uid = [[NSNumber alloc]initWithInteger:1];
    aUser.name = @"zhang";
    aUser.age = [[NSNumber alloc]initWithInteger:10];
    aUser.rank = [[NSNumber alloc]initWithInteger:10];
    aUser.role = [[NSNumber alloc]initWithInteger:10];
    aUser.sex = [[NSDecimalNumber alloc]initWithInt:1];
    aUser.tel = nil;
    aUser.image = nil;
    NSError *error = nil;
    if (![[self manageObjectContext] save:&error]) {
        NSLog(@"Unresolved error %@, %@",error,[error userInfo]);
        abort();
    }else{
        NSLog(@"insert successful!");
    }
    
}


- (NSMutableDictionary *)getAllUserList
{
    
    NSMutableDictionary *allItemDic = [[NSMutableDictionary alloc] init];
//    DBManager *dbManager = [DBManager shareDBManagerInstance];
    sqlite3_stmt *stmt = nil;
    if (sqlite3_open([_databasePath UTF8String], &itemsDB) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(itemsDB, "select * from User ", -1, &stmt, nil) == SQLITE_OK)
        {
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                NSMutableArray *itemListArray = [[NSMutableArray alloc]initWithCapacity:1];
                NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:1];
//                NSMutableString *str;
                NSString *uid;
//                NSString *sex;
//                NSString *age;
//                NSString *name;
//                NSString *role;
//                NSString *tel;
//                NSString *rank;
//                NSString *image;
                for (int i =0 ; i < sqlite3_column_count(stmt); i++) {
                    NSString *attr = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, i)];
                    [itemListArray addObject:attr];
                }
                uid = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 0)];
//                str = [[NSMutableString alloc]initWithString:uid];
//                
//                sex = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,1)];
//                [str stringByAppendingString:sex];
//                
//                age = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,2)];
//                [str stringByAppendingString:age];
//                
//                name = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,3)];
//                [str stringByAppendingString:name];
//
//                role = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,4)];
//                [str stringByAppendingString:role];
//
//                tel = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,5)];
//                [str stringByAppendingString:tel];
//
//                rank = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,6)];
//                [str stringByAppendingString:rank];
//
//                image = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt,7)];
//                [str stringByAppendingString:image];
                
//                NSLog(@"%@",str);
//                itemListArray = [[NSMutableArray alloc] initWithObjects:uid,sex,age,name,role,tel,rank,image,nil];
                [allItemDic setValue:itemListArray forKey:uid];
            }
        }
    }
    sqlite3_finalize(stmt);
    sqlite3_close(itemsDB);
    return allItemDic;
}


-(void)fetchPlayer{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity ;
    //相当于where查询条件
    NSPredicate *predicate;
    predicate = [NSPredicate predicateWithFormat:@"number < 5 and name like %@",@"I*"];
    [fetchRequest setPredicate:predicate];
}

@end












